package com.nero.security;

import com.nero.bean.PO.TbAdmin;
import com.nero.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * Created by Nero on 18/8/21.
 */
//@Component
public class ShiroDbRealm extends AuthorizingRealm {
//    @Resource
    public IUserService userServiceImpl;

    public IUserService getUserServiceImpl() {
        return userServiceImpl;
    }

    public void setUserServiceImpl(IUserService userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    /**
     * 获取授权信息
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String username = principalCollection.getPrimaryPrincipal().toString();
        //List roleList = userService.getRoles();
        info.addRole("oper");//oper,admin,manager
        info.addRole("admin");
        info.addRole("manager");
        //List permissionList = userService.getPermissions();
        //info.addStringPermission("oper:add");
        //info.addStringPermission("oper:del");
        info.addStringPermission("oper:add");
        return info;
    }

    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
//        System.out.println("进行登录验证");
        //获得令牌——基于用户名和密码的令牌
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//        System.out.println("username: " + token.getUsername());
//        System.out.println("password: " + String.copyValueOf(token.getPassword()));
//        System.out.println("impl==null? " + (userServiceImpl == null));
//        System.out.println("impl's class: " + userServiceImpl.getClass().toString());
        //从令牌中可以取出用户名
        String accountName = token.getUsername();
        TbAdmin userInDB = userServiceImpl.findByUsername(accountName);
//        TbAdmin userInDB = new TbAdmin();
//        userInDB.setPassword("123456");
//        userInDB.setUsername("admin");
        // 让shiro框架去验证账号密码
        if (userInDB != null) {
            return new SimpleAuthenticationInfo(userInDB.getUsername(), userInDB.getPassword(), getName());
        }
        return null;
    }
}
